package com.yangfan.juc.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.StampedLock;
import java.util.stream.IntStream;

/**
 * @description: 显示锁、重入锁
 * @author: yangfan
 * @date: Created in 2020/3/26 0026 14:13
 * @modified By:
 *
 *
 * 获取锁的 有尝试获取锁
 *      {@link ReentrantLock#tryLock()}
 *      {@link ReentrantLock#tryLock(long, TimeUnit)}  尝试获取锁 等待 所设置的类型与时间
 *
 */
public class ReentrantLockExample {


    private static ReentrantLock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();


    public static void main(String[] args) {

        IntStream.range(0, 2).forEach(i -> new Thread(() -> test()).start());

    }


    public static void test(){

        if(lock.tryLock()){
            try {
                System.out.println(Thread.currentThread().getName() + "拿到锁了");
                TimeUnit.SECONDS.sleep(5);
                System.out.println(Thread.currentThread().getName() + "释放锁了");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }



    };





}
